package com.fractalist.man.web.action;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fractalist.base.core.web.BaseActionSupport;
import com.fractalist.man.base.SqlUtils;
import com.fractalist.man.constants.ManConstants;
import com.fractalist.man.service.IConfigService;
import com.fractalist.man.service.IPurviewService;
import com.fractalist.man.service.IUserGroupService;
import com.fractalist.man.util.PHPSerializer;

@Controller
@Scope("prototype")
@ParentPackage("default")
@Namespace(value = "/")
@Action(value = "isstSet")
public class IsstAction extends BaseActionSupport {

	private static final long serialVersionUID = -6711050766680570618L;

	@SuppressWarnings("unused")
	private static final Logger logger = Logger.getLogger(IsstAction.class);

	@Autowired
	private IConfigService configService;
	
	@Autowired
	private IUserGroupService userGroupService;
	
	@Autowired
	private IPurviewService purviewService;

	/**
	 * 管理系统参数配置
	 */
	@Action(value = "/viewConfig", interceptorRefs = @InterceptorRef("withAuthStack"))
	public String viewConfig() {
		List<Map<String, Object>> configList = configService
				.queryList("select * from " + configService.getTableName()
						+ " order by type");
		// getRequest().setAttribute("configList", configList);
		if (configList != null && configList.size() > 0) {
			Map<String, Object> map = null;
			for (int i = 0; i < configList.size(); i++) {
				map = configList.get(i);
				// System.out.println(map.get("varName")+":"+map.get("value"));
				getRequest().setAttribute((String) map.get("varName"),
						map.get("value"));
			}
		}
		return dispatcher("/config.jsp");
	}

	/**
	 * 保存参数
	 */
	@SuppressWarnings("rawtypes")
	@Action(value = "/saveConfig", interceptorRefs = @InterceptorRef("withAuthStack"))
	public String saveConfig() {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("state", 0);
		result.put("msg", "操作成功");
		Enumeration eNames = getRequest().getParameterNames();
		String key = null;
		String value = null;
		while (eNames.hasMoreElements()) {
			key = (String) eNames.nextElement();
			value = getRequest().getParameter(key);
			System.out.println(key + ":" + value);
			configService.update(SqlUtils.genderUpdateSql(
					configService.getTableName(), "varName='" + key + "'",
					"value='" + value + "'"));
		}
		return renderJson(result);
	}

	/**
	 * PHP网站权限分配--用户组列表差性能
	 */
	@Action(value = "/phpRoleList", interceptorRefs = @InterceptorRef("withAuthStack"))
	public String phpRoleList() {
		getRequest().setAttribute("userTypeMap", ManConstants.USER_TYPE_MAP);
		return dispatcher("/phpRoleList.jsp");
	}
	
	/**
	 * PHP网站权限分配--权限分配
	 */
	@SuppressWarnings("rawtypes")
	@Action(value = "/phpRightDispatch", interceptorRefs = @InterceptorRef("withAuthStack"))
	public String phpRightDispatch() {
		//取页面参数
		String groupId = getRequest().getParameter("groupId");
		getRequest().setAttribute("groupId", groupId);
		//查询PHP资源
		List<Map<String, Object>> purviewList = purviewService
				.queryList("select * from " + purviewService.getTableName()
						+ " where status='1' order by type,listorder");
		
		//查询当前用户类型已配置的PHP资源
		Map<String, Object> tmp = userGroupService.queryOneRow("select * from "
				+ userGroupService.getTableName()+" where groupId='"+groupId+"'");
		if (tmp != null && tmp.size() > 0) {
			String selectedPurview = (String)tmp.get("purview");
			//获取该用户类型已配置的PHP资源字符串
			if(selectedPurview!=null&&!"".equals(selectedPurview))
			{
				try
				{
					//按规则解码
					Object  obj = PHPSerializer.unserialize(selectedPurview.getBytes());
					if(obj instanceof ArrayList)
					{
						//循环判断PHP资源是否在已配置资源之列，如果是则设置相应参数为1，前台页面将勾选该资源
						ArrayList objArray = (ArrayList)obj;
						if(purviewList!=null&&purviewList.size()>0)
						{
							Map<String, Object> map = null;
							String key = null;
							for(int i=0;i<purviewList.size();i++)
							{
								map = purviewList.get(i);
								key = map.get("class")+"_"+map.get("method");
								if(objArray.contains(key))
								{
									map.put("checked", "1");
								}
							}
						}
					}
				}
				catch(IllegalAccessException e)
				{
					e.printStackTrace();
				}
			}
		}
		//设置PHP资源列表
		getRequest().setAttribute("purviewList", purviewList);
		return dispatcher("/phpRightDispatch.jsp");
	}
	
	/**
	 * PHP网站权限分配--权限分配
	 */
	@Action(value = "/saveDispatch", interceptorRefs = @InterceptorRef("withAuthStack"))
	public String saveDispatch() {
		//取页面参数
		String groupId = getRequest().getParameter("groupId");
		//取页面勾选的资源
		String[] purviewArray = getRequest().getParameterValues("purviewChk");
		//保存勾选资源权限到数据库
		if(purviewArray!=null&&purviewArray.length>0)
		{
			byte[] byteArray = PHPSerializer.serialize(purviewArray);
			String purview = new String(byteArray);
			//调用业务接口将权限资源保存到数据库
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("purview", purview);
			userGroupService.update(SqlUtils.genderUpdateSql(
					userGroupService.getTableName(), "groupId = " + groupId,
					SqlUtils.genderConditionsByType(paramMap, ",")));
		}
		return dispatcher("/isstSet/phpRightDispatch.action");
	}

}
